﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Pikapika.Models.ViewModels.Home;
using Pikapika.Models;
using System.Data.Objects;

namespace Pikapika.Controllers
{
    public class HomeController : LayoutPageControllerBase
    {
        [OutputCache(Duration=600, VaryByParam="")]
        public ActionResult Index()
        {
            var result = new IndexModel();
            using (var ctx = new PikapikaDBEntities())
            {
                ctx.Connection.Open();
                result.LatestNovels = ctx.GetLatestNovels();

                var weekEnd = DateTime.UtcNow.Date;
                var weekStart = weekEnd.AddDays(-7);
                result.WeeklyHottestNovels = (from rec in ctx.NovelChapterHitCountRecords
                                              where rec.Date > weekStart && rec.Date <= weekEnd
                                              group rec by rec.NovelId into g
                                              let n = new IndexWeeklyHotestNovel
                                              {
                                                  Novel = (from n in ctx.Novels
                                                           where n.Id == g.Key
                                                           select n).FirstOrDefault(),
                                                  HitCount = g.Sum(r => r.HitCount)
                                              }
                                              orderby n.HitCount descending
                                              select n).Take(Properties.Settings.Default.HomeRankingDisplayCount).ToList();

                ObjectQuery<Annotation> annotationQuery = (ObjectQuery<Annotation>)(from ann in ctx.Annotations
                                                           orderby ann.Id descending
                                                           select ann).Take(Properties.Settings.Default.HomeLatestAnnotationCount);

                annotationQuery = annotationQuery.Include("NovelChapter.NovelVolume.Novel");
                result.LatestAnnotations = annotationQuery.ToList();
            }
            return View(result);
        }

    }
}
